/* eslint-disable */
import axios from 'axios'

import env from '../../build/env'
import { vm } from '@/main.js'

let util = {}

util.permissionSwitch = true

util.title = function(title) {
    window.document.title = title
}

//密码加密公钥，为空时不加密
const rsaPubKey = ''
// 浏览器语言获取
const browserLanguage = localStorage.getItem('ELEMENT_LANGUAGE') || window.navigator.language || 'en-US'
util.browserLanguage = browserLanguage

// util.getLocalUrl = window.location.protocol + '//' + window.location.host

util.getLocalUrl ="http://172.20.7.34:30004"

// util.getLocal = util.getLocalUrl + '/oss-gateway'
util.getLocal = util.getLocalUrl

const ajaxUrl = process.env.SERVER_BASEURL ? process.env.SERVER_BASEURL : env === 'development' ? util.getLocal : env === 'production' ? util.getLocal : util.getLocal

const statisticUrl = process.env.STATISTIC_URL ? process.env.STATISTIC_URL : 'https://s.ctbiyi.com/img'

const userName = 'oss-vue-example'

util.baseUrl = ajaxUrl

util.ajax = axios.create({
    baseURL: ajaxUrl,
    timeout: 60000
})
let loading = null
let requestCount = 0
util.ajax.interceptors.request.use(
    function(config) {
        // 每请求一个接口，请求数量加一，打开遮罩
        if (config.config && config.config.showLoading) {
            requestCount++
            loading = vm.$loading({
                fullscreen: true,
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.3)'
            })
        }

        config.headers.Authorization = localStorage.token
        config.withCredentials = true;
        return config
    },
    function(error) {
        // 请求失败的处理
        return Promise.reject(error)
    }
)

util.ajax.interceptors.response.use(
    function(res) {
        //在这里对返回的数据进行处理
        if (!res.config.url.includes('refreshToken')) {
            //记录ajax调用的时间
            sessionStorage.lastAjaxTime = new Date().getTime()
        }
        // 每请求成功一个接口，请求数量减一，数量为零关闭遮罩
        if (res.config.config && res.config.config.showLoading) {
            setTimeout(function() {
                requestCount--
                if (requestCount <= 0) {
                    loading.close()
                }
            }, 10)
        }

        return res
    },
    function(error) {
        // 统一处理接口超时
        let originalRequest = error.config
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
            // eslint-disable-next-line
            loading.close()
            return Promise.reject('timeout')
        }

        // 每请求成功一个接口，请求数量减一，数量为零关闭遮罩
        if (error.response.config.config && error.response.config.config.showLoading) {
            setTimeout(function() {
                requestCount--
                if (requestCount <= 0) {
                    loading.close()
                }
            }, 10)
        }
        if (error.response.data.status === 401 || error.response.status === 401) {
            vm.$message({ type: 'warning', message: '当前用户未登录' })
            setTimeout(() => {
                let url = util.getLocalUrl + '/oss-portal/#/login'
                window.open(url, '_top') // 返回的时候有问题，跳出登录是没有头部
            }, 500)
        } else {
            if (error.response.data.status === 403) {
                vm.$message({ type: 'warning', message: error.response.data.message })
            }
        }
        return Promise.reject(error)
    }
)

util.ajaxMethodWidthParams = function(url, method, params) {
    let instance = axios.create()
    return new Promise((resolver, reject) => {
        var res = resolver
        util.ajax({
            method: method,
            url: url,
            data:params,
            config: {
                showLoading: true
            }
        })
            .then((response) => {
                res(response.data)
            })
            .catch((error) => {
                reject(error)
            })
    })
}

util.ajaxGetData = function(url, params) {
    let instance = axios.create()
    instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

    return new Promise((resolve, reject) => {
        var p = new URLSearchParams()
        for (var key in params) {
            p.append(key, params[key])
        }
        util.ajax
            .post(url, p)
            .then((response) => {
                resolve(response.data)
            })
            .catch((error) => {
                reject(error)
            })
    })
}

// 针对后台规范，强制使用@RequestBody编写的方法
util.ajaxPostData = function(url, params, isMask = true) {
    let instance = axios.create()
    instance.defaults.headers.post['Content-Type'] = 'application/json'

    return new Promise((resolve, reject) => {
        util.ajax({
            method: 'post',
            url: url,
            data: params,
            config: {
                showLoading: isMask
            }
        })
            .then((response) => {
                resolve(response.data)
            })
            .catch((error) => {
                reject(error)
            })
    })
}
// 针对文件下载，强制使用@RequestBody编写的方法
util.downloadPostData = function(url, params, isMask = true) {
    let instance = axios.create()
    return new Promise((resolve, reject) => {
        util.ajax({
            method: 'get',
            url: url,
            data: params,
            responseType: 'blob',
            config: {
                showLoading: isMask
            }
        })
            .then((response) => {
                resolve(response)
            })
            .catch((error) => {
                reject(error)
            })
    })
}
util.ajaxMethod = function(method, url, params, headers) {
    let Params = {}
    let Data = {}
    let reg1 = new RegExp('^(G|g)(E|e)(T|t)$')
    let reg2 = new RegExp('^(D|d)(E|e)(L|l)(E|e)(T|t)(E|e)')
    if (reg1.test(method) || reg2.test(method)) {
        Params = params
    } else {
        Data = params
    }
    return new Promise((resolve, reject) => {
        util.ajax({
            method: method,
            url: url,
            params: Params,
            data: Data,
            headers: headers || {},
            config: {
                showLoading: true
            }
        })
            .then((response) => {
                resolve(response.data)
            })
            .catch((error) => {
                reject(error)
            })
    })
}
export default util
